#!/bin/bash

if [ -z "$1" ]; then
    echo "请传入边端SN号作为参数"
    exit 1
fi

sn="$1"
conf_file="/etc/rtty.conf"
sn_file="/userfs/sn.txt"

# 备份原文件（可选）
# cp "$conf_file" "${conf_file}.bak"

# 替换 DEVICE_ID 行中的旧值为新 SN（只替换 DEVICE_ID= 后的内容）
sed -i "s/^DEVICE_ID=.*/DEVICE_ID=$sn/" "$conf_file"

# 写入 /userfs/sn.txt
echo "$sn" > "$sn_file"

# 强制同步到磁盘
sync

# 校验：检查 DEVICE_ID 是否已正确设置
actual_id=$(grep "^DEVICE_ID=" "$conf_file" | cut -d'=' -f2)

if [ "$actual_id" = "$sn" ] && [ -f "$sn_file" ] && [ "$(cat "$sn_file")" = "$sn" ]; then
    echo "SN号写入成功: $sn"
    exit 0
else
    echo "SN号写入失败！当前 DEVICE_ID=$actual_id，期望=$sn"
    exit 1
fi